package lib.translation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import lib.base.EgoSystem;
import lib.json.JSONUnserializer;

public class Translator
{
	private HashMap<String,String> _languageRelation;
	private String language;
	
	public Translator(String l)
	{
		_setLanguage(l);
	}
	
	@SuppressWarnings("unchecked")
	private void _setLanguage(String l)
	{
		language = l;
		String txt="";
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(EgoSystem.config.get("language-files").toString()+language+".json"));
			String zeile;
			
			while ((zeile = br.readLine()) != null) 
			{
				txt += zeile;
			}
			_languageRelation = (HashMap<String, String>) new JSONUnserializer().unserialize(txt);
			
		}catch(Exception i) 
		{
			_languageRelation = new HashMap<String, String>(); 
		}
	}
	
	static public ArrayList<String> getLanguages()
	{
		ArrayList<String> langs = new ArrayList<String>();
		
		langs.add("en"); // en is default language
		
		File dir = new File(EgoSystem.config.get("language-files").toString());
		File[] files = dir.listFiles();
		for (int i=0; i<files.length; i++)
		{
			if (files[i].getName().matches("^[a-z]{2}\\.json"))
			{
				langs.add(files[i].getName().substring(0, 2));
			}
		}
		
		return langs;
	}
	
	public String translate(String original) throws Exception 
	{	
		String translated = null;
		translated = _languageRelation.get(original);
		if (translated == null)
		{
			// if there is no translation for this word, display the original
			translated = original;
		}
		return translated;
	}
	
}
